<?php

namespace App\Imports;


use App\Models\Project;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class LatLngExcel implements ToCollection
{

    protected $projectId;

    public function __construct($projectId)
    {
        $this->projectId = $projectId;
    }

    public function collection(Collection $rows)
    {
        // 如果需要去除表头
        unset($rows[0], $rows[1], $rows[2]);
        // $rows 是集合对象
        $this->checkData($rows);
    }

    public function checkData($rows)
    {
        //注意导入的excel只能有一个sheet，多个sheet会报数据为空这个异常
        if (!count($rows)) {
            throw new \Exception('导入数据不能为空');
        }
        // 校验数据的正确信息
        DB::beginTransaction();
        try {
            foreach ($rows as $k => $row) {
                $data[] = $row->get(0) . ',' . $row->get(1);
            }
            Project::where('id', $this->projectId)->update(['coords' => $data]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new  \Exception($e->getMessage());
        }
        DB::commit();
        return true;
    }

}
